package com.paw.generator;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * @author lvzihai
 * @date 2021/7/7
 **/
public class HelloWorldVelocity {

  public static void main(String[] args) {
    // 初始化模板引擎
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocityEngine.init();
    // 获取模板文件
    Template template = velocityEngine.getTemplate("templates/helloVelocity.vm");
    // 设置变量
    VelocityContext ctx = new VelocityContext();
    ctx.put("name", "Velocity");
    User user = new User();
    user.setName("zhang san");
    user.setPhone("18612345678");
    ctx.put("user", user);
    List list = new ArrayList();
    list.add("1");
    list.add("2");
    ctx.put("list", list);
    // 输出
    StringWriter sw = new StringWriter();
    template.merge(ctx,sw);
    System.out.println(sw.toString());
  }

}
